package com.example.searchviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;

public class MainActivity extends AppCompatActivity {

    SearchView searchView;
    ListView listView;
    private String[] mData = {"aaa","xzx","qwdas","sdfsdf"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    public void initView(){
        listView = findViewById(R.id.listView);
        searchView = findViewById(R.id.SearchView);
        //默认展开
        searchView.onActionViewCollapsed();
        searchView.setQueryHint("请输入要搜索的内容");

        listView.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,mData));
        listView.setTextFilterEnabled(true);

        //设置文本监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            //当点击搜索时触发此事件
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            //当搜索内容改变时触发此方法
            @Override
            public boolean onQueryTextChange(String newText) {
                if (!TextUtils.isEmpty(newText)){
                    listView.setFilterText(newText);
                }else{
                    listView.clearTextFilter();
                }
                return false;
            }
        });
    }
}